package cc.site.main.service.account;

import cc.site.common.exception.FineException;
import cc.site.common.utils.JwtUtils;
import cc.site.common.utils.R;
import cc.site.config.redis.utils.RedisCache;
import cc.site.main.bean.TblUser;
import cc.site.main.bean.vo.UserVo;
import cc.site.main.service.TblUserService;
import cc.site.main.tools.SecurityTools;
import cc.site.security.bean.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @CREATE By yangruomao On 2024/4/18 上午10:58
 */
@Service
public class AccountService {

    @Autowired
    private TblUserService userService;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SecurityTools securityUtils;

    @Autowired
    private AuthenticationManager authenticationManager;


    public R register(UserVo vo) {
        // 校验用户名不能重复
        QueryWrapper<TblUser> w = new QueryWrapper<>();
        w.eq("username", vo.getUsername());
        if (!userService.list(w).isEmpty()) {
            return R.error().message("用户名被注册过了");
        }
        TblUser user = new TblUser();
        BeanUtils.copyProperties(vo, user);
        user.setPassword(securityUtils.getSecret(user.getPassword()));
        userService.save(user);

        return R.ok().message("注册成功").data("user", user);
    }

    public R login(String username, String password) {
        TblUser user = new TblUser();
        user.setUsername(username);
        user.setPassword(password);

        // 封装认证对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate == null) {
            throw new FineException(R.ERROR, "认证失败");
        }

        // 获取用户信息-获取token-完整用户信息存入redis
        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        Integer userId = loginUser.getUser().getId();

        String jwt = JwtUtils.getJwtToken(userId.toString(), username);
        redisCache.setCacheObject("login:"+userId, loginUser, 100, TimeUnit.HOURS);

        return R.ok().data("token", jwt).data("user", user);
    }
}
